package at.playbox.server.businesslogic;

import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import at.playbox.server.entity.Response;
import at.playbox.server.entity.User;

public class UserService
{
	// HashMap um User im RAM zu halten
	public static Map<String, User> userMap = new HashMap<String, User>();

	public UserService()
	{
		User user1 = new User();
		if (!userMap.containsKey("test"))
		{
			// test User wird automatisch angelegt (muss vor richtiger
			// Installation gelöscht werden --> Sicherheitsrisiko!)
			user1.setUsername("test");
			user1.setSalt("5f6c437e3f5549dcac330f90f152eab7");
			user1.setHash("075874a1beb8102419d87ffce56f90be3e238bb6");
			userMap.put("test", user1);
		}
	}

	// Methode um User zu registrieren
	public Response register(String username, String salt, String hash)
	{
		Response response = new Response();
		if (checkCharsOfUsername(username))
		{
			if (getUserByUsername(username) == null)
			{
				User user = new User();
				user.setUsername(username);
				user.setHash(hash);
				user.setSalt(salt);
				userMap.put(user.getUsername(), user);

				for (Map.Entry<String, User> e : userMap.entrySet())
				{
					User tmpuser = (User) e.getValue();
					System.out.println("register " + e.getKey() + " = " + tmpuser.getUsername() + ";" + tmpuser.getSalt() + ";" + tmpuser.getHash());
				}
				response.setResponse("OK");
			}
			else
			{
				response.setResponse("[Fault] Dublicate Username!");
			}
			return response;
		}
		else
		{
			response.setResponse("[Fault] Wrong Characters within the Username! Max. 10 Characters, [a-zA-Z0-9]!");
			return response;
		}

	}

	// Methode um Passwort zu ändern
	public Response changePassword(String username, String salt, String hash)
	{
		Response response = new Response();
		if (getUserByUsername(username) != null)
		{
			User user = userMap.get(username);
			user.setHash(hash);
			user.setSalt(salt);
			userMap.put(user.getUsername(), user);
			response.setResponse("OK");
		}
		else
		{
			response.setResponse("[Fault] Username doesn't exist!");
		}
		return response;
	}

	// Methode gibt User-Objekt anhand des Usernamens zurück
	public User getUserByUsername(String username)
	{
		if (userMap.containsKey(username))
		{
			User user = userMap.get(username);
			System.out.println(user.getUsername() + " getUserByUsername");
			return user;
		}
		else
		{
			return null;
		}
	}

	// Methode überprüft ob Username korrekt ist
	public boolean checkCharsOfUsername(String username)
	{
		return username.matches("[a-zA-Z0-9]*");
	}

	public String createXML(Object obj) throws JAXBException
	{
		StringWriter sw = new StringWriter();
		JAXBContext context = JAXBContext.newInstance(obj.getClass());
		Marshaller marshaller = context.createMarshaller();
		marshaller.marshal(obj, sw);
		return sw.toString();
	}

}
